package com.gx.smart.building.ui.repair.fragment

import android.app.Activity
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.blankj.utilcode.util.TimeUtils
import com.bumptech.glide.Glide
import com.gx.smart.building.R
import com.gx.smart.building.databinding.FragmentRepairDetailBinding
import com.gx.smart.building.ui.common.adapter.ImageAdapter
import com.gx.smart.building.ui.common.fragment.BaseMVVMFragmentAudioV2
import com.gx.smart.building.ui.common.util.SpannableUtil
import com.gx.smart.building.ui.photo.activity.CustomActivity
import com.gx.smart.building.ui.photo.fragment.PhotoPreviewFragment
import com.gx.smart.building.ui.photo.model.ImageViewInfo
import com.gx.smart.building.ui.repair.adapter.RepairDetailHandleAdapter
import com.gx.smart.building.ui.repair.common.CommonHelper
import com.gx.smart.building.ui.repair.viewmodel.RepairViewModel
import com.gx.smart.lib_http.BuildConfig
import com.huishi.gx.ib.grpc.lib.ib.app.workorder.v1.dto.WorkOrderFileDto
import com.previewlibrary.GPreviewBuilder

class RepairDetailFragment : BaseMVVMFragmentAudioV2<RepairViewModel>() {
    private lateinit var viewBinding: FragmentRepairDetailBinding
    private lateinit var imageAdapter: ImageAdapter
    private lateinit var imageAdapter2: ImageAdapter
    private lateinit var processAdapter: RepairDetailHandleAdapter
    private val imageViewInfoList: MutableList<ImageViewInfo> = mutableListOf()
    private var isRunning: Boolean = false

    override fun onBindLayout(): Int = R.layout.fragment_repair_detail

    override fun getToolbarTitle(): String = "工单详情"

    override fun onBindViewModel(): Class<RepairViewModel> = RepairViewModel::class.java


    override fun initContentView(root: ViewGroup) {
        viewBinding = FragmentRepairDetailBinding.inflate(layoutInflater, root, true)
    }

    override fun initContent() {
        super.initContent()
        imageAdapter = ImageAdapter(requireContext())
        viewBinding.recyclerView.adapter = imageAdapter
        imageAdapter.setItemClickListener { _, position ->
            run {
                val bundle = Bundle()
                bundle.putSerializable("className", PhotoPreviewFragment::class.java)
                GPreviewBuilder.from((context as Activity?)!!)
                    .to(CustomActivity::class.java, bundle)
                    .setData(imageViewInfoList)
                    .setIsScale(true)
                    .setCurrentIndex(position)
                    .setSingleFling(true) //是否在黑屏区域点击返回
                    .setDrag(true) //是否禁用图片拖拽返回
                    .setType(GPreviewBuilder.IndicatorType.Number) //指示器类型
                    .start()
            }
        }
        processAdapter = RepairDetailHandleAdapter(requireContext())
        viewBinding.recyclerViewProgress.adapter = processAdapter
        imageAdapter2 = ImageAdapter(requireContext())
        viewBinding.attachmentRecyclerView.adapter = imageAdapter2
    }

    override fun initData() {
        viewModel.queryWorkOrderDetail(requireActivity().intent.getStringExtra("id")!!)
            .observe(viewLifecycleOwner) { it ->
                viewBinding.status.text = CommonHelper.getStatus(it.status)
                submitByStatus(it.status)
                viewBinding.orderCode.text = it.orderCode
                viewBinding.orderTypeName.text = it.orderTypeName
                viewBinding.orderSubTypeName.text = it.orderSubTypeName
                viewBinding.orderSourceName.text = it.orderSourceName
                viewBinding.areaName.text = it.areaName
                viewBinding.releaseUserName.text = if (it.releaseUserPhone.isNotBlank()) {
                    "${it.releaseUserName}(${it.releaseUserPhone})"
                } else {
                    "${it.releaseUserName}"
                }
                SpannableUtil(requireContext()).initSpanPhone(viewBinding.releaseUserName)
                viewBinding.createTime.text =
                    TimeUtils.millis2String(it.createTime, "yyyy-MM-dd HH:mm:ss")
                viewBinding.assetName.text = it.assetName
                viewBinding.description.text = it.description
                //2 音频
                val voiceList: List<WorkOrderFileDto> = listOf()
//                    it.workOrderFileDtoList.filter { item -> item.fileType == 2 }
                if (voiceList.isNullOrEmpty()) {
                    viewBinding.voiceLayout.visibility = View.GONE
                } else {
                    viewBinding.voiceLayout.visibility = View.VISIBLE
                    val duration = voiceList[0].showTimes
                    val url = BuildConfig.FILE_UPLOAD_URL + voiceList[0].fileUrl
                    viewBinding.voiceDuration.text = "${duration / 1000}''"
                    viewBinding.voiceLayout.setOnClickListener {
                        isRunning = !isRunning
                        if (isRunning) {
                            audioPlay(url)
                            Glide.with(this).asGif().load(R.drawable.ic_voice_play)
                                .into(viewBinding.voicePlay)
                        } else {
                            audioPlayPause()
                            Glide.with(this).load(R.mipmap.ic_voice_play)
                                .into(viewBinding.voicePlay)
                        }
                    }
                }
                //图片
//                imageAdapter.refresh(it.workOrderFileDtoList.filter { item -> item.fileType == 1 }
//                    .map { workOrderFile ->
//                        BuildConfig.FILE_UPLOAD_URL + workOrderFile.fileUrl
//                    })
//                imageViewInfoList.clear()
//                it.workOrderFileDtoList.filter { item -> item.fileType == 1 }
//                    .forEach { workOrderFile ->
//                        val imageViewInfo =
//                            ImageViewInfo(BuildConfig.FILE_UPLOAD_URL + workOrderFile.fileUrl)
//                        imageViewInfoList.add(imageViewInfo)
//                    }
                //工单流程
                processAdapter.refresh(it.workOrderEventDto)
                val workOrderEvent =
                    it.workOrderEventDto.findLast { event -> event.eventCode == "process_task" }
                if (workOrderEvent == null) {
                    viewBinding.handleResultLayout.visibility = View.GONE
                } else {
                    viewBinding.handleResultLayout.visibility = View.VISIBLE
                    viewBinding.suggestion.text = workOrderEvent.opinion
//                    imageAdapter2.refresh(workOrderEvent.workOrderEventFileDtoList.map {
//                        BuildConfig.FILE_UPLOAD_URL + it.fileUrl
//                    })
                }
            }
    }

    private fun submitByStatus(status: String) {
        when (status) {
            "task_receive" -> {
                viewBinding.submitLayout.visibility = View.VISIBLE
                viewBinding.save.visibility = View.VISIBLE
                viewBinding.save.setOnClickListener {
                    findNavController().navigate(R.id.action_repairDetailFragment_to_waitingSubmitFragment,
                        Bundle().apply {
                            putString("id", requireActivity().intent.getStringExtra("id"))
                        }
                    )
                }
            }
            "task_process" -> {
                viewBinding.submitLayout.visibility = View.VISIBLE
                viewBinding.save.visibility = View.GONE
                viewBinding.back.visibility = View.VISIBLE
                viewBinding.back.setOnClickListener {
                    findNavController().navigate(R.id.action_repairDetailFragment_to_processingBackFragment,
                        Bundle().apply {
                            putString("id", requireActivity().intent.getStringExtra("id"))
                        }
                    )
                }
                viewBinding.process.visibility = View.VISIBLE
                viewBinding.process.setOnClickListener {
                    findNavController().navigate(R.id.action_repairDetailFragment_to_processingSubmitFragment,
                        Bundle().apply {
                            putString("id", requireActivity().intent.getStringExtra("id"))
                        }
                    )
                }
                viewBinding.transform.visibility = View.VISIBLE
                viewBinding.transform.setOnClickListener {
                    findNavController().navigate(R.id.action_repairDetailFragment_to_processingTransformFragment,
                        Bundle().apply {
                            putString("id", requireActivity().intent.getStringExtra("id"))
                        }
                    )
                }
                viewBinding.submit.visibility = View.VISIBLE
                viewBinding.submit.setOnClickListener {
                    findNavController().navigate(
                        R.id.action_repairDetailFragment_to_processingSuspendFragment,
                        Bundle().apply {
                            putString("id", requireActivity().intent.getStringExtra("id"))
                        }
                    )
                }
            }
            "task_suspend_review",
            "task_suspend" -> {
                viewBinding.back.visibility = View.GONE
                viewBinding.process.visibility = View.GONE
                viewBinding.transform.visibility = View.GONE
                viewBinding.submit.visibility = View.GONE
                viewBinding.submitLayout.visibility = View.VISIBLE
                viewBinding.save.visibility = View.VISIBLE
                viewBinding.save.text = "解挂"
                viewBinding.save.setOnClickListener {
                    findNavController().navigate(
                        R.id.action_repairDetailFragment_to_suspendSubmitFragment,
                        Bundle().apply {
                            putString("id", requireActivity().intent.getStringExtra("id"))
                        }
                    )
                }
            }

            "task_review",
            "task_complete" -> {
                viewBinding.submitLayout.visibility = View.GONE
            }

        }
    }

    override fun onPause() {
        super.onPause()
        isRunning = false
        Glide.with(this).load(R.mipmap.ic_voice_play).into(viewBinding.voicePlay)
    }

    override fun playComplete() {
        isRunning = false
        Glide.with(this).load(R.mipmap.ic_voice_play).into(viewBinding.voicePlay)
    }

}